package com.farah.lease.web.admin.custom.converter;

import com.farah.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * @Author 不爱跑步的法拉韶
 * @Date 2024-06-22__15:38
 * @Description 将字符串转换为枚举
 **/
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new Converter<String, T>() {
            @Override
            public T convert(String code) {
                for(T enumConstant : targetType.getEnumConstants()){
                    if(enumConstant.getCode().equals(Integer.valueOf(code))){
                        return enumConstant;
                    }
                }
                throw new IllegalArgumentException("无法将" + code + "转换为" + targetType);
            }
        };
    }
}
